const {slugify} = require('transliteration');
const Base = require('./base.js');
const md5 = require("md5");

const helper = require('think-helper');

module.exports = class extends Base {

    async _initialize() {
        await super._initialize();
    }

    async indexAction() {
        this.assign(
            {
                status: [{key: 0, title: '关闭'}, {key: 1, title: '开启'}]
            }
        );
        await this.display('admin/comment/index');
    }

    async updateAction() {

        const id = this.query('id');
        const status = this.query('status');
        const ids = id.split(',');

        for (let i in ids) {
            await this.mongoose('Comment').add({id: ids[i], status: status});
        }

        this.json('/admin/comment/index', '保存成功');
    }

    async tableAction() {

        const p = this.query('page') || 1;

        const id = this.post('id');
        const status = this.post('status');
        const keywords = this.post('keywords');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (!helper.isEmpty(keywords)) {
            queryParams = {
                $or: [
                    {title: {$regex: keywords, $options: "$i"}},
                    {module: {$regex: keywords, $options: "$i"}},
                    {model: {$regex: keywords, $options: "$i"}},
                ]
            }
        }

        //等值查询
        if (!helper.isEmpty(status)) {
            queryParams = Object.assign(queryParams, {status: status});
        }

        //id属性要单独查找,不支持正则表达式
        if (!helper.isEmpty(id)) {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.fail('没找到符合条件的记录');
                return;
            }
        }

        console.log(queryParams);

        const pageSize = 20;
        const Model = this.mongoose('Comment');
        let pageEntity = await Model.findPage({
            page: p,
            pageSize: pageSize
        }, 'commenter', queryParams, {}, {createdAt: 'asc'});

        // think.logger.debug(pageEntity);
        this.assign(
            {
                records: pageEntity.data,
                pager: super.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
            }
        )
        await this.display('admin/comment/table');
    }

    async disable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Comment');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('/admin/comment/index', '禁用评论成功');

    }

    async enable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Comment');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            //this.changeModelField('admin/admin/Administrator', i, 'status', 1);
        }
        this.success('/admin/comment/index', '恢复成功');
    }

    async delete() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Comment');
        const CommentModel = this.model('admin/Comment');
        for (const i of ids) {
            await CommentModel.remove({
                rowId: i,
            });

            await Model.findByIdAndRemove(i).exec();
        }
        this.success('/admin/comment/index', '删除评论成功');
    }

    async add() {

        if (this.isPost()) {

            const comment = this.post;

            comment.pinyin = slugify(comment.title);

            await this.model('admin/Comment').saveOrUpdate(comment);

            this.json('/admin/comment/index', '保存成功');
        } else {

            if (this.query.id) {
                //查出关联的封面图片信息
                const comment = await this.model('admin/Comment').findOne({_id: this.query.id}).populate('cover');
                if (comment) {
                    await this.render('admin/comment/add', {comment: comment});
                } else {
                    this.logger.warn(`文章${this.query.id}不存在`);
                    this.redirect('/admin/comment/index?err=' + encodeURI('文章不存在'));
                }
            } else {
                await this.render('admin/comment/add');
            }
        }
    }
}
